/** file Filterclipping.cpp
    author belot.nicolas
*/

#include "FilterClipping.h"
#include <cmath>
#include <iostream>

namespace libtrckr {

string FilterClipping::HowToTune(){
	return "Multiband X -5 +5; Spin -5 +5, Spin -10 +0; Spin 0 +10; Spin -5 +5;Bitrate";

}

FilterClipping::FilterClipping():preGain(0),floor(0),ratio(1),postGain(0),EQ(){

}

FilterClipping::FilterClipping(const FilterClipping& f):preGain(f.preGain),floor(f.floor),ratio(f.ratio),postGain(f.postGain),EQ(f.EQ){

}


void FilterClipping::Tune(DynArray<int> conf){
	//conf[0] => size of the EQ;
	DynArray<int> equal(conf[0]+2,0);
	std::cout << equal.size() << std::endl;
	equal[0]=conf[0];
	for(uint i=1;i<=conf[0];i+=2){
		//EQ work with preGain...
		equal[i]=conf[i]+conf[conf[0]+1];
		equal[i+1]=conf[i+1];
	}
	std::cout << equal.size() << std::endl;
	//preGain=pow(10.0, ((conf[conf[0]+1]+0.)/100.0)/20.0);
	floor=pow(10.0, (conf[conf[0]+2]+0.0)/20. );
	ratio = conf[conf[0]+3]+0.0;
	postGain = pow(10.0, ((conf[conf[0]+4]+0.)/100.0)/20.0);
	equal[conf[0]+1]=conf[conf[0]+5];
	EQ.Tune(equal);

}

void FilterClipping::Init() {
	EQ.Init();
}

Buffer &FilterClipping::Preview(Buffer &b){
	b = EQ.Preview(b);
	for(uint i=0;i<b.size();i++){
		//preGain
		//b[i]*=preGain;
		//Clipping
		double signe = b[i]>0.?1.:-1.;
		if(signe*b[i]>floor){
			b[i]*=signe;
			if(ratio==0.){
				b[i]=floor; //hard clipping
			}else{
				b[i] = floor * pow(b[i] / floor, 1.0 / ratio );
			}
			b[i]*=signe;
		}
		//postGain
		b[i]*=postGain;
	}
	return b;
}

Buffer& FilterClipping::Execution(Buffer&b){
	return Preview( b);
}

double *FilterClipping::Preview(double *data, int size){
	data = EQ.Preview(data,size);
	for(uint i=0;i<size;i++){
		//preGain
		//data[i]*=preGain;
		//Clipping
		if(data[i]>floor){
			if(ratio==0){
				data[i]=floor; //hard clipping
			}else{
				data[i] = floor * pow(data[i] / floor, 1.0 / ratio );
			}
		}
		//postGain
		data[i]*=postGain;
	}
	return data;

}

double *FilterClipping::Execution(double *data, int size){
	return Preview(data,size);
}

}

